package mod.luckymod.fluids;

import com.simibubi.create.AllTags;
import com.simibubi.create.foundation.data.CreateRegistrate;
import com.tterrag.registrate.builders.FluidBuilder;
import com.tterrag.registrate.util.entry.FluidEntry;
import mod.luckymod.AllCreativeModeTabs;
import mod.luckymod.Luckymod;
import mod.luckymod.blocks.NaOHFluidBlock;
import net.createmod.catnip.theme.Color;
import net.minecraft.core.BlockPos;
import net.minecraft.core.BlockSource;
import net.minecraft.core.dispenser.DefaultDispenseItemBehavior;
import net.minecraft.core.dispenser.DispenseItemBehavior;
import net.minecraft.core.particles.ParticleTypes;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.entity.item.ItemEntity;
import net.minecraft.world.item.BucketItem;
import net.minecraft.world.item.DispensibleContainerItem;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
import net.minecraft.world.level.BlockAndTintGetter;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.DispenserBlock;
import net.minecraft.world.level.material.FluidState;
import net.minecraft.world.level.material.MapColor;
import net.minecraftforge.common.ForgeMod;
import net.minecraftforge.fluids.FluidInteractionRegistry;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.ForgeFlowingFluid;
import org.joml.Vector3f;

public class AllFluids {
    private static final CreateRegistrate REGISTRATE = Luckymod.registrate();
    static {
        REGISTRATE.setCreativeTab(AllCreativeModeTabs.BASE_CREATIVE_TAB);
    }
    public static void register() {
    }
    private static void registerFluidDispenseBehavior(BucketItem bucket) {
        DispenserBlock.registerBehavior(bucket, DISPENSE_FLUID);
    }
    private static final DispenseItemBehavior DEFAULT = new DefaultDispenseItemBehavior();
    private static final DispenseItemBehavior DISPENSE_FLUID = new DefaultDispenseItemBehavior(){
        @Override
        protected ItemStack execute(BlockSource pSource, ItemStack pStack) {
            DispensibleContainerItem dispensibleContainerItem = (DispensibleContainerItem) pStack.getItem();
            BlockPos pos = pSource.getPos().relative(pSource.getBlockState().getValue(DispenserBlock.FACING));
            Level level = pSource.getLevel();
            if (dispensibleContainerItem.emptyContents(null, level, pos, null, pStack)) {
                return new ItemStack(Items.BUCKET);
            }
            return DEFAULT.dispense(pSource, pStack);
        }
    };
    // 注册流体交互 - 腐蚀性流体可以转化其他流体
    public static void registerFluidInteractions() {
        // 氢氧化钠可以中和酸性流体
        FluidInteractionRegistry.addInteraction(ForgeMod.WATER_TYPE.get(),
                new FluidInteractionRegistry.InteractionInformation(
                        AllFluids.NAOH_Entry.get().getFluidType(),
                        fluidState -> {
                            // 只有当水是流动状态时才反应
                            if (fluidState.isSource()) {
                                return Blocks.AIR.defaultBlockState();
                            }return fluidState.createLegacyBlock();
                        }
                ));

        // 与熔岩反应生成黑曜石（强碱与硅酸盐反应）
        FluidInteractionRegistry.addInteraction(ForgeMod.LAVA_TYPE.get(),
                new FluidInteractionRegistry.InteractionInformation(
                        AllFluids.NAOH_Entry.get().getFluidType(),
                        fluidState -> Blocks.OBSIDIAN.defaultBlockState()
                ));
    }
    public static final FluidEntry<ForgeFlowingFluid.Flowing> NAOH_Entry =
            REGISTRATE.standardFluid("naoh",
                            // 使用自定义的FluidType工厂，设置雾颜色和距离
                            Liquid.create(
                                    0xFF6B6B, // 浅红色雾 (RGB: 255, 107, 107)
                                    1f/7f // 雾距离乘数
                            ))
                    .lang("氢氧化钠")
                    .properties(b -> b
                            .viscosity(1000)    // 和水一样的粘度
                            .density(2000)      // 比水密度大
                            .temperature(800)  // 中等温度
                    )
                    .fluidProperties(p ->
                            p.levelDecreasePerBlock(2)  // 快速扩散
                            .tickRate(10)               // 快速更新
                            .slopeFindDistance(8)       // 较大扩散范围
                            .explosionResistance(100f)
                    )
                    .tag(AllTags.forgeFluidTag("sodium_liquid"))
                    .source(ForgeFlowingFluid.Source::new)
                    .block((fluid, props) -> new NaOHFluidBlock(fluid::get, props))
                    .properties(p -> p
                            .mapColor(MapColor.WATER) // 方块地图颜色
                            .lightLevel(state -> 0)         // 不发光
                    )
                    .build()
                    .bucket()
                    .onRegister(AllFluids::registerFluidDispenseBehavior)
                    .lang("氢氧化钠")
                    .properties(p -> p
                            .craftRemainder(Items.BUCKET)    // 桶装流体
                            .stacksTo(1)
                    )
                    .build()
                    .register();
    public static class Liquid extends com.simibubi.create.AllFluids.TintedFluidType {
        public static FluidBuilder.FluidTypeFactory create(int fogColor, Float fogDistance) {
            return (p, s, f) -> {
                Liquid fluidType = new Liquid(p, s, f);
                fluidType.fogColor = new Color(fogColor, false).asVectorF();
                fluidType.fogDistance = fogDistance;
                return fluidType;
            };
        }
        @Override
        public void setItemMovement(ItemEntity entity) {
            // 检查物品是否为钠物品
            ItemStack stack = entity.getItem();
            if (!isSodiumItem(stack)) {
                // 非钠物品被腐蚀消失
                entity.discard();
                // 可选：播放腐蚀效果
                if (!entity.level().isClientSide) {
                    entity.level().addParticle(ParticleTypes.SMOKE,
                            entity.getX(), entity.getY(), entity.getZ(),
                            0, 0.1, 0);
                }
            } else {
                // 钠物品正常漂浮
                super.setItemMovement(entity);
            }
        }
        private boolean isSodiumItem(ItemStack stack) {
            // 检查物品是否为钠物品
            // 您需要根据您的钠物品标签或注册名来实现这个检查
            return stack.is(AllTags.forgeItemTag("sodium/equipment")) ||
                    stack.is(AllTags.forgeItemTag("metal/sodium")) ||
                    stack.is(AllTags.forgeItemTag("sodium/weapon"));
        }
        public Vector3f fogColor;
        public Float fogDistance;
        Liquid(Properties properties, ResourceLocation stillTexture, ResourceLocation flowingTexture) {
            super(properties, stillTexture, flowingTexture);
        }
        @Override
        protected int getTintColor(FluidStack stack) {
            return NO_TINT;
        }

        @Override
        public int getTintColor(FluidState state, BlockAndTintGetter world, BlockPos pos) {
            return 0x00ffffff;
        }
        @Override
        protected Vector3f getCustomFogColor() {
            return fogColor;
        }

        @Override
        protected float getFogDistanceModifier() {
            return fogDistance;
        }
    }
}